package com.reform.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.reform.pojo.project.ProjectMember;
import com.reform.mapper.ProjectMemberMapper;
import com.reform.res.Result;
import com.reform.res.ResultCode;
import com.reform.service.IProjectMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reform.utils.VerifycUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mortale
 * @since 2021-07-20
 */
@Service
public class ProjectMemberServiceImpl extends ServiceImpl<ProjectMemberMapper, ProjectMember> implements IProjectMemberService {

    @Autowired
    ProjectMemberMapper projectMemberMapper;



    @Override
    public Integer deleteProjectMemberByProId(String proId) {
        Map<String, Object> map = new HashMap<>();
        map.put("pro_id", proId);
        return projectMemberMapper.deleteByMap(map);
    }


    @Override
    public Integer creatProjectMemberList(List<ProjectMember> projectMemberList) {
        int res = 0;
        for (ProjectMember projectMember : projectMemberList) {
            res += projectMemberMapper.insert(projectMember);
        }
        if (res != projectMemberList.size()) {
            return -1;
        }
        return res;
    }

    @Override
    public Integer updateProjectMemberList(List<ProjectMember> projectMemberList) {
        int res = 0;
        for (ProjectMember projectMember : projectMemberList) {
            projectMemberMapper.updateById(projectMember);
            res++;
        }
        return res;
    }

    @Override
    public Result deleteProjectMemberByMemberId(String member_id) {
        if (projectMemberMapper.deleteById(member_id) > 0)
            return Result.success(ResultCode.SUCCESS);
        return Result.failure(ResultCode.FAILURE);
    }

    @Override
    public Result insertProjectMember(String projectMembers) {
        List<ProjectMember> projectMemberList;
        try {
            projectMemberList = JSON.parseArray(projectMembers, ProjectMember.class);
        } catch (JSONException e) {
            return Result.failure(ResultCode.PARAM_JSON_IS_WRONG, e.getMessage());
        }
        int res = 0;
        for (ProjectMember projectMember : projectMemberList) {
            if (!VerifycUtils.verifyNullOrEmptyUtils(projectMember.getProId())) {
                return Result.failure(ResultCode.PARAM_IS_MISSING);
            }
        }
        for (ProjectMember projectMember : projectMemberList) {
            System.out.println(projectMember);
            res += projectMemberMapper.insert(projectMember);
        }
        if (res != projectMemberList.size()) {
            return Result.failure(ResultCode.FAILURE);
        }
        return Result.success(ResultCode.SUCCESS);
    }
}
